﻿using System.Collections.Generic;
using AutoMapper;
using Qask.Data.Core;

namespace Qask.Service.Core
{
    public static class CustomMapper
    {
        public static void ConfigureCustomMapper()
        {
            Mapper.Initialize(cfg => cfg.SourceMemberNameTransformer = ConvertNames);
            
            // mappings required in post service.
            Mapper.CreateMap<Post, PostViewModel>();
            Mapper.CreateMap<PostViewModel, Post>().FixDestination(new[] { "PostType", "AspNetUser" });
            
            // mappings required in account service.
            Mapper.CreateMap<TimeZone, TimeZoneViewModel>();

            // mappings created for updating timezone in account management page.
            Mapper.CreateMap<AspNetUser, AspNetUserModel>();
            Mapper.CreateMap<AspNetUserModel, AspNetUser>().ForMember(x => x.Posts, y=> y.Ignore()).ForMember(x => x.TimeZone, y => y.Ignore());

            Mapper.AssertConfigurationIsValid();
        }

        public static TDestination Map<TSource, TDestination>(TSource source)
        {
            try
            {
                return Mapper.Map<TSource, TDestination>(source);
            }
            catch (AutoMapperMappingException ex)
            {

                throw new AutoMappingException(ex.Message, ex);
            }

        }

        public static IEnumerable<TDestination> Map<TSource, TDestination>(IEnumerable<TSource> source)
        {
            try
            {
                return Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(source);
            }
            catch (AutoMapperMappingException ex)
            {

                throw new AutoMappingException(ex.Message);
            }
        }

        public static TDestination DynamicMap<TSource, TDestination>(TSource source)
        {
            try
            {
                return Mapper.DynamicMap<TSource, TDestination>(source);
            }
            catch (AutoMapperMappingException ex)
            {

                throw new AutoMappingException(ex.Message);
            }
        }

        #region private methods
        private static string ConvertNames(string inputString)
        {
            // transform the sections into w/e you need     
            return inputString.Replace("_", "");
        }
        #endregion
    }
}